<template>
  <section class="shenghuohuiEdit">
    <el-dialog :title="dialogtitle" :visible.sync="dialogVisible" width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
      <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container">
        <div id="shenghuohuiEditTable">
          <table cellspacing="0" cellpadding="0" class="mytable">
            <tr>
              <th>班子成员姓名</th>
              <td>
                <!--postForm.idNumber目前存储的为一个json对象转成的字符串，key为idNumber和name，如果是从领导表读取的则还有zhiwu，初始为null，如果领导表数据删除了，也需要保留本表填写的数据-->
                <el-form-item prop="idNumber">
                  <el-select v-model="postForm.idNumber" placeholder="请选择" style="width:130px;">
                    <el-option label="请选择..." :value="null" />
                    <el-option v-for="(item, index) in newLeaders" :key="'1_'+index" :label="item.name" :value="JSON.stringify({idNumber:item.idNumber,name:item.name})">
                      <span style="float: left">{{ item.name }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px;padding-left:10px;">{{ item.zhiwu }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </td>
              <th>谈话时间</th>
              <td>
                <el-form-item prop="shijian">
                  <el-date-picker v-model="postForm.shijian" placeholder="请选择时间" value-format="yyyy-MM-dd" />
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>谈话对象</th>
              <td>
                <el-form-item prop="duixiang">
                  <el-input v-model="postForm.duixiang" style="width:200px" />
                </el-form-item>
              </td>
              <th>谈话类型</th>
              <td>
                <el-form-item prop="leixing">
                  <el-select v-model="postForm.leixing" placeholder="请选择" style="width:250px;">
                    <el-option v-for="(item, index) in lxList" :key="'1_'+index" :label="(index+1)+'.'+item" :value="item" />
                  </el-select>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>备注</th>
              <td colspan="3">
                <el-input v-model="postForm.remark" style="width:100%" :maxlength="shhRemarkLength" />
              </td>
            </tr>
            <tr>
              <th></th>
              <td colspan="3">
                <el-button type="primary" :loading="loading" @click="submitForm">保存</el-button>
              </td>
            </tr>
          </table>
        </div>
      </el-form>
    </el-dialog>
    <div v-if="pageLoading" style="margin:20px;">正在加载...</div>
    <div v-else>
      <div style="margin:10px;"><span style="font-weight:bolder;padding-right:20px;">谈心谈话</span>
          <el-button type="success" @click="addData" icon="el-icon-plus">新增</el-button>
          <el-button icon="el-icon-download" :loading="btnLoading" @click="exportExcel">导出Excel模板</el-button>
          <el-upload class="upload-demo" :before-upload="beforeAvatarUpload" name="file" :file-list="fileList"
            :show-file-list="false"
            :data="{'shenghuohuiunitId':shenghuohuiunitId}"
            :action="this.$http.defaults.baseURL +this.$http.defaults.shenghuohuiAPI + 'api/newHqTanhua/saveImport'"
            with-credentials
            :multiple="false"
            :on-success="importSuccess"
            :on-error='uploaderror'
            style="display:inline"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
            <el-button type="primary" icon="el-icon-upload">导入Excel数据</el-button>
          </el-upload>
        <!-- <el-button-group>
          <el-button type="primary" icon="el-icon-arrow-up" :loading="btnLoading" @click="moveData(true)" :disabled="!moveUpFlag">上移</el-button>
          <el-button type="primary" icon="el-icon-arrow-down" :loading="btnLoading" @click="moveData(false)" :disabled="!moveDownFlag">下移</el-button>
        </el-button-group> -->
      </div>
      <el-table :data="tableData" highlight-current-row v-loading="listLoading" style="width: 100%;" :height="tableHeight" border ref="multipleTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="banziPersonName" label="班子成员姓名" width="120" />
        <el-table-column prop="shijian" label="谈话时间" width="120" />
        <el-table-column prop="leixing" label="谈话类型" min-width="120" />
        <el-table-column prop="duixiang" label="谈话对象" width="120" />
        <el-table-column prop="remark" label="备注" width="120" />
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="primary" @click="modData(scope.row.id)" size="medium" style="margin:10px 0;" icon="el-icon-edit">修改</el-button>
            <el-popconfirm title="确定删除该信息吗？" @confirm="removeData(scope.row.id)" style="margin:10px 0;">
              <el-button slot="reference" type="danger" size="medium" :loading="btnLoading" icon="el-icon-delete">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </section>
</template>
<script>
import global from '../Global'
const defaultForm = {
  idNumber: null, // 初始值为空
  banziPersonName: '',
  shijian: '',
  duixiang: '',
  leixing: '',
  remark: '',
  id: null
}
export default {
  props: {
    timestamp: ''
  },
  data () {
    const validateRequire = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      newLeaders: [], // 避免重复添加已删除的人员，创建一个新的领导列表用于生成下拉选项
      pageLoading: true,
      shenghuohuiunitId: '',
      fileList: [],
      lxList: [],
      shhRemarkLength: global.shhRemarkLength,
      shhItemLength: global.shhItemLength,
      moveUpFlag: false,
      moveDownFlag: false,
      leaders: [],
      tableName: 'newHqTanhua',
      dialogVisible: false,
      dialogtitle: '新增',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        idNumber: [{ validator: validateRequire }],
        shijian: [{ validator: validateRequire }],
        duixiang: [{ validator: validateRequire }],
        leixing: [{ validator: validateRequire }]
      },
      tableHeight: 100,
      multipleSelection: [],
      btnLoading: false,
      listLoading: false,
      tableData: [],
      index: null
    }
  },
  watch: {
    timestamp (val) {
      this.pageLoading = true
      this.getLeaders()
      this.getData()
    }
  },
  methods: {
    importSuccess (res) {
      if (res.result && res.result.length > 0) {
        const h = this.$createElement
        let vnodelist = []
        res.result.forEach(item => {
          vnodelist.push(h('p', null, item))
        })
        this.$message({
          message: h('p', null, vnodelist),
          type: 'error',
          showClose: true
        })
      } else {
        this.getData()
      }
    },
    uploaderror (err) {
      this.$message({
        message: '导入失败:' + err,
        type: 'error'
      })
    },
    beforeAvatarUpload (file) {
      console.log('文件类型')
      console.log(file.name)
      const isFormat = file.name.indexOf('.xlsx') > 0 || file.name.indexOf('.XLSX') > 0
      // const isLt5M = file.size / 1024 / 1024 < 500
      if (!isFormat) {
        this.$message.error('上传文件只能是 .xlsx 格式!')
      }
      return isFormat
    },
    exportExcel () {
      window.open(this.$http.defaults.baseURL + this.$http.defaults.shenghuohuiAPI + `api/newHqTanhua/downloadTemplate`)
    },
    getLeaders () {
      this.shenghuohuiunitId = localStorage.getItem('shenghuohuiunitId')
      let para = {
        shenghuohuiunitId: this.shenghuohuiunitId,
        pageNum: 1,
        pageSize: 2000
      }
      // var personParams = { Page: 0, Pagenum: 20, Personname: '', Unitkey: '', Sortkey: '', Isace: true, timestamp: new Date().getTime() }
      this.$http
        .post(this.$http.defaults.shenghuohuiAPI + `api/newHqLingdao/queryByPage`, para)
        .then(response => {
          if (response.data.success === true) {
            // 避免idnumber大小写问题，重建领导数组，并精简为只保留name,idNumber,zhiwu
            this.leaders = response.data.result.records.map(item => {
              return {name: item.name, idNumber: item.idnumber, zhiwu: item.zhiwu}
            })
          } else {
            console.log('获取数据失败:' + response.data.message)
            this.$message({
              message: '获取数据失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    getLxList () {
      this.$http
        .get(this.$http.defaults.shenghuohuiAPI + `api/newDict/list`)
        .then(response => {
          if (response.data.success === true) {
            this.lxList = response.data.result
          } else {
            console.log('获取数据失败:' + response.data.message)
            this.$message({
              message: '获取数据失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    moveData (flag) {
      let para = {
        id: this.multipleSelection[0].id,
        shenghuohuiunitId: localStorage.getItem('shenghuohuiunitId'),
        up: flag
      }
      this.$http.post(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/updateOrder`, para).then(response => {
        console.log(response.data.success)
        if (response.data.success === true) {
          this.btnLoading = false
          this.getData(this.multipleSelection[0].id)
        } else {
          console.log('调整顺序失败:' + response.data.message)
          this.$message({
            message: '调整顺序失败:' + response.data.message,
            type: 'error'
          })
          this.btnLoading = false
        }
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '调整顺序失败:' + error,
          type: 'error'
        })
        this.btnLoading = false
      })
    },
    handleSelectionChange (val) {
      this.moveUpFlag = false
      this.moveDownFlag = false
      this.multipleSelection = val
      if (this.multipleSelection.length === 1) {
        this.moveUpFlag = true
        this.moveDownFlag = true
        if (this.tableData.findIndex(item => item.id === this.multipleSelection[0].id) === 0) {
          this.moveUpFlag = false
        }
        if (this.tableData.findIndex(item => item.id === this.multipleSelection[0].id) === this.tableData.length - 1) {
          this.moveDownFlag = false
        }
      }
    },
    removeData (id) {
      let ids = []
      if (id) {
        ids = [id]
      } else {
        ids = this.multipleSelection.map(item => item.id)
      }
      if (ids.length > 0) {
        this.$http.post(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/remove`, {ids: ids}).then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
          this.getData()
        })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    submitForm () {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true
          // 创建下拉框选中的对象person，如果下拉框没change，对象为object，如果change，从下拉框取出来的值为string，需要转为json对象，保持一致
          let person = typeof (this.postForm.idNumber) === 'string' ? JSON.parse(this.postForm.idNumber) : this.postForm.idNumber
          let para = {
            id: this.postForm.id,
            shenghuohuiunitId: localStorage.getItem('shenghuohuiunitId'),
            idNumber: person.idNumber,
            banziPersonName: person.name,
            shijian: this.postForm.shijian,
            duixiang: this.postForm.duixiang,
            leixing: this.postForm.leixing,
            remark: this.postForm.remark
          }
          this.$http.post(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/save`, para).then(response => {
            console.log(response.data.success)
            if (response.data.success === true) {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              if (this.$refs['postForm']) {
                this.$refs['postForm'].resetFields()
              }
              this.dialogVisible = false
              this.loading = false
              this.getData()
            } else {
              console.log('保存失败:' + response.data.message)
              this.$message({
                message: '保存失败:' + response.data.message,
                type: 'error'
              })
              this.loading = false
            }
          }).catch(error => {
            console.log(error)
            this.$message({
              message: '保存失败:' + error,
              type: 'error'
            })
            this.loading = false
          })
        }
      })
    },
    addData () {
      this.dialogtitle = '新增'
      this.dialogVisible = true
      this.postForm = Object.assign({}, defaultForm)
      if (this.$refs['postForm']) {
        this.$refs['postForm'].resetFields()
      }
      // 新增时也需要复制领导数组
      this.newLeaders = [...this.leaders]
    },
    modData (id) {
      this.id = id
      this.dialogtitle = '编辑'
      this.dialogVisible = true
      this.infoLoading = true
      this.$http
        .get(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/getById?id=` + id)
        .then(response => {
          this.infoLoading = false
          if (response.data.success === true) {
            console.log('获取成功')
            this.postForm = response.data.result
            // idNumber通过接口取出的为身份证号字符串，需要转化为json对象，并去领导数组中匹配，如果已被删除，需要将对象push到领导数组的最后，postForm.idNumber最终转化为字符串付给下拉框
            this.postForm.idNumber = {idNumber: this.postForm.idNumber, name: this.postForm.banziPersonName}
            this.newLeaders = [...this.leaders]
            if (!this.leaders.find(item => item.idNumber === this.postForm.idNumber.idNumber && item.name === this.postForm.idNumber.name)) {
              this.newLeaders.push(this.postForm.idNumber)
            }
            this.postForm.idNumber = JSON.stringify(this.postForm.idNumber)
          } else {
            console.log('获取数据失败:' + response.data.message)
            this.$message({
              message: '获取数据失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
          this.infoLoading = false
        })
    },
    toggleSelection (id) {
      this.$nextTick(() => {
        if (id) {
          let newrow = this.tableData.find(item => item.id === id)
          console.log(newrow)
          this.$refs.multipleTable.toggleRowSelection(newrow)
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      })
    },
    getData (id) {
      this.listLoading = true
      let para = {
        shenghuohuiunitId: localStorage.getItem('shenghuohuiunitId'),
        pageNum: 1,
        pageSize: 2000
      }
      // var personParams = { Page: 0, Pagenum: 20, Personname: '', Unitkey: '', Sortkey: '', Isace: true, timestamp: new Date().getTime() }
      this.$http
        .post(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/queryByPage`, para)
        .then(response => {
          this.pageLoading = false
          this.listLoading = false
          if (response.data.success === true) {
            console.log('获取成功')
            this.tableData = response.data.result.records
            if (id) {
              this.toggleSelection(id)
            }
          } else {
            console.log('获取数据失败:' + response.data.message)
            this.$message({
              message: '获取数据失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
          this.pageLoading = false
          this.listLoading = false
        })
    },
    tableresize (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      obj.$nextTick(function () {
        obj.tableHeight = clientHeight - 200
      })
    }
  },
  mounted () {
    console.log('this.shhRemarkLength')
    console.log(this.shhRemarkLength)
    this.getLeaders()
    this.getLxList()
    this.getData()
    this.tableresize(this)
    window.onresize = () => {
      // 通过捕获系统的onresize事件触发我们需要执行的事件
      this.tableresize(this)
    }
  }
}
</script>

<style>
  .shenghuohuiEdit .el-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  }
  .shenghuohuiEdit .el-table td, .el-table th{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体'
  }
  .el-table{
    border-top: 1px solid #95B8E7 !important;
  }
  .el-table--border th, .el-table--border td {
    border-right: 1px solid #95B8E7 !important;
  }
  .el-table th.is-leaf, .el-table td {
    border-bottom: 1px solid #95B8E7 !important;
  }
  #shenghuohuiEditTable .mytable{
    border-top: 1px solid #74A6CC;
    border-left: 1px solid #74A6CC;
    margin: 10px;
    width: calc(100% - 20px);
    font-size:var(--size14) !important;
    font-family: '宋体'
  }
  #shenghuohuiEditTable .mytable th,
  #shenghuohuiEditTable .mytable td{
    height: auto;
    padding: 10px;
    border-right: 1px solid #74A6CC;
    border-bottom: 1px solid #74A6CC;
    vertical-align:top;
    line-height: 150%;
  }
  #shenghuohuiEditTable .mytable th{
    background:#C0DCF1;
    width:150px;
    vertical-align: middle;
  }
</style>
